const WXAPI = require('apifm-wxapi')
const TOOLS = require('../../utils/tools.js')
const AUTH = require('../../utils/auth')
const CONFIG = require('../../config.js')
const APP = getApp()

Page({
  data: {
    qj: wx.getStorageSync("qj") || 'bz',
    zdydh: wx.getStorageSync("zdydh") || '',
    zdylogo: wx.getStorageSync("zdylogo") || '',
    dh_tap_index: 3,
    menuList: [],
    allList: [],
    array: [],
    selectedIndex: 0,
    selectedIndex2: undefined,
    caseIndex: '-1',
    case3Index: '-1',
    caseIndexList: [],
    showPop: false,
    caseIndexName0: '',
    caseIndexName1: '',
    caseIndexName2: '',
    caseIndexName3: '',
    caseIndexName4: '',
    caseIndexName5: '',
    articleList: [],
    page: 1,
    pageSize: 12,
    isLoading: false,
    noMoreData: false,
    k: '',
    category: [],
    forceRefresh: false,
    refreshKey: 1,
    case_3navid: '',
    // 新增：用于节流控制
    scrollThrottle: false
  },

  onLoad: function (e) {
    this.setData({
      selectedIndex: e.selectedIndex || 0,
      caseIndex: e.caseIndex || '-1',
      case_3navid: e.case_3navid || '',
    });
    console.log("selectedIndex:", this.data.selectedIndex);
    console.log("caseIndex:", this.data.caseIndex);
    console.log("case_3navid:", this.data.case_3navid);

    // 先加载分类数据，再还原选中状态
    this.category();
  },

  onShow: function () {
    const currentQj = wx.getStorageSync("qj") || 'bz';
    if (currentQj !== this.data.qj) {
      this.setData({ qj: currentQj });
      // 如果切换了环境，重新加载数据
      this.category();
    }
  },

  async category() {
    try {
      const res = await WXAPI.cmsCategories()
      if (res.code !== 0) {
        wx.showToast({ title: res.msg || '获取分类失败', icon: 'none' });
        return;
      }

      let temp = res.data;
      let tree = this.buildTree(temp);

      // 获取id是200484下面的数据
      let targetCategory = tree.find(ele => ele.id == 200484);

      if (!targetCategory || !targetCategory.children || targetCategory.children.length === 0) {
        wx.showToast({ title: '未找到指定分类数据', icon: 'none' });
        return;
      }

      this.setData({
        category: targetCategory.children,
        allList: temp,
        array: targetCategory.children.map(ele =>
          this.data.qj === 'hz' || this.data.qj === 'bz' ? ele.name : ele.remark
        ),
        menuList: targetCategory.children[0]?.children || []
      });

      if (this.data.case_3navid) {
        const caseIndexList = this.data.allList.filter(ele => ele.pid == this.data.category[this.data.selectedIndex].children[this.data.caseIndex].id);
        this.setData({
          caseIndexList,
        });
      }

      // 初始化加载文章
      this.resetArticleList();
      this.loadArticles();
    } catch (err) {
      console.error('分类加载失败：', err);
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    }
  },

  buildTree(flatData) {
    if (!Array.isArray(flatData)) return [];

    const nodeMap = {};
    const rootNodes = [];

    flatData.forEach(node => {
      nodeMap[node.id] = { ...node, children: [] };
    });

    flatData.forEach(node => {
      const currentNode = nodeMap[node.id];
      const parentId = node.pid;

      if (parentId === 0) {
        rootNodes.push(currentNode);
      } else if (nodeMap[parentId]) {
        nodeMap[parentId].children.push(currentNode);
      }
    });

    return rootNodes;
  },

  article_detail(e) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      wx.navigateTo({
        url: `/packageYt/goods/detail?id=${id}`,
      });
    } else {
      wx.showToast({ title: '参数错误', icon: 'none' });
    }
  },

  // 重置文章列表数据
  resetArticleList() {
    this.setData({
      articleList: [],
      page: 1,
      noMoreData: false
    });
  },

  // 加载文章列表（核心方法）
  async loadArticles() {
    if (this.data.isLoading || this.data.noMoreData) return;

    this.setData({ isLoading: true });

    try {
      let categoryId = '200484';

      if (this.data.case_3navid) {
        categoryId = this.data.case_3navid;
      } else if (this.data.caseIndex !== '-1' && this.data.caseIndex !== undefined) {
        const selectedCat = this.data.category[this.data.selectedIndex];
        if (selectedCat && selectedCat.children && selectedCat.children[this.data.caseIndex]) {
          categoryId = selectedCat.children[this.data.caseIndex].id;
        }
      } else {
        const selectedCat = this.data.category[this.data.selectedIndex];
        if (selectedCat) {
          categoryId = selectedCat.id;
        }
      }

      const res = await WXAPI.cmsArticles({
        categoryId,
        k: this.data.k ? this.data.k.trim() : '',
        page: this.data.page,
        pageSize: this.data.pageSize
      });

      if (res.code === 700) {
        this.setData({
          noMoreData: true,
          isLoading: false
        });
        return;
      }

      if (res.code === 0) {
        const newArticles = res.data.result || [];
        const oldArticles = this.data.articleList;
        const total = res.data.totalRow || 0;

        this.setData({
          articleList: oldArticles.concat(newArticles),
          page: this.data.page + 1,
          noMoreData: this.data.articleList.length + newArticles.length >= total
        });
      } else {
        wx.showToast({ title: res.msg || '加载失败', icon: 'none' });
      }
    } catch (err) {
      console.error('加载失败：', err);
      wx.showToast({ title: '网络异常', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  // 处理滚动到底部加载
  onReachBottom() {
    // 使用节流防止多次触发
    if (!this.data.scrollThrottle) {
      this.scrollThrottle = true;
      this.loadArticles();
      // 300ms后重置节流状态
      setTimeout(() => {
        this.scrollThrottle = false;
      }, 300);
    }
  },

  case_nav_footer(e) {
    const name = e.currentTarget.dataset.name;
    const nameEn = e.currentTarget.dataset.nameEn;
    const currentCaseIndex = this.data.caseIndex;

    if (this.data.k.indexOf(name) === -1) {
      this.setData({
        k: this.data.k + name + ','
      });
    }

    // 处理之前选中项的清除
    const caseIndexNames = ['caseIndexName0', 'caseIndexName1', 'caseIndexName2', 'caseIndexName3', 'caseIndexName4', 'caseIndexName5'];
    if (currentCaseIndex >= 0 && currentCaseIndex < caseIndexNames.length) {
      const prevName = this.data[caseIndexNames[currentCaseIndex]];
      if (prevName) {
        this.setData({
          k: this.data.k.replace(prevName, '')
        });
      }

      // 设置新选中项
      this.setData({
        [caseIndexNames[currentCaseIndex]]: this.data.qj === 'hz' || this.data.qj === 'bz' ? name : nameEn,
        showPop: false
      });
    }

    // 处理多余逗号
    this.setData({
      k: this.data.k.replace(/,+/g, ',').replace(/^,|,$/g, '') // 同时去除首尾逗号
    });

    // 重新加载数据
    this.resetArticleList();
    this.loadArticles();
  },

  case_nav(e) {
    const temp = e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;

    if (id) {
      const caseIndexList = this.data.allList.filter(ele => ele.pid == id);
      this.setData({
        caseIndex: temp,
        case_3navid: '',
        caseIndexList,
        case3Index: '-1'
      });

      // 重新加载数据
      this.resetArticleList();
      this.loadArticles();
    }
  },

  case_3nav(e) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      this.setData({
        case_3navid: id,
        case3Index: e.currentTarget.dataset.index
      });

      // 重新加载数据
      this.resetArticleList();
      this.loadArticles();
    }
  },



  bindPickerChange: function (e) {
    const selectedIndex = e.detail.value;
    this.setData({
      caseIndexList: [],
      forceRefresh: true,
      case_3navid: '',
      caseIndex: '-1',
      case3Index: '-1'
    }, () => {
      setTimeout(() => {
        this.setData({
          refreshKey: this.data.refreshKey + 1,
          forceRefresh: false,
          selectedIndex,
          page: 1,
          articleList: [],
          noMoreData: false,
          menuList: this.data.category[selectedIndex]?.children || []
        });
        this.loadArticles();
      }, 300); // 缩短延迟时间，提升体验
    });
  },

  zdy_top_nav() {
    wx.navigateTo({
      url: '/pages/xl/index',
    });
  },

  dh_tap(e) {
    const temp = e.currentTarget.dataset.id;
    this.setData({ dh_tap_index: temp });

    const urlMap = [
      '/packageYt/index/index',
      '/packageYt/case/index',
      '/packageYt/ting/index',
      '/packageYt/goods/index',
      '/packageYt/my/index'
    ];

    if (temp >= 0 && temp < urlMap.length) {
      wx.reLaunch({ url: urlMap[temp] });
    }
  },

  async getGoodsList(categoryId, append) {
    if (categoryId === 0) categoryId = "";

    wx.showLoading({ title: '' });
    try {
      const res = await WXAPI.goodsv2({
        categoryId,
        page: this.data.curPage,
        pageSize: this.data.pageSize
      });

      if (res.code === 404 || res.code === 700) {
        let newData = { loadingMoreHidden: false };
        if (!append) newData.goods = [];
        this.setData(newData);
        return;
      }

      let goods = append ? this.data.goods : [];
      const hidden_goods_index = wx.getStorageSync('hidden_goods_index') || [];

      for (const item of res.data.result) {
        if (!hidden_goods_index.includes(item.id)) {
          goods.push(item);
        }
      }

      this.setData({
        loadingMoreHidden: true,
        goods
      });
    } catch (err) {
      console.error('商品列表加载失败：', err);
    } finally {
      wx.hideLoading();
    }
  },

  onShareAppMessage: function () {
    let params = 'selectedIndex=' + this.data.selectedIndex;
    if (this.data.caseIndex != '-1') {
      params += '&caseIndex=' + this.data.caseIndex;

      if (this.data.case_3navid) {
        params += '&case_3navid=' + this.data.case_3navid;
      }
    }


    const sharePath = `/packageYt/goods/index?${params}`;
    console.log('分享路径：', sharePath); // 可通过控制台查看参数是否完整
    return {
      title: `"${wx.getStorageSync('mallName')}" ${wx.getStorageSync('share_profile')}`,
      path: sharePath,
    };
  },

  onShareTimeline() {
    let params = 'selectedIndex=' + this.data.selectedIndex;
    if (this.data.caseIndex != '-1') {
      params += '&caseIndex=' + this.data.caseIndex;

      if (this.data.case_3navid) {
        params += '&case_3navid=' + this.data.case_3navid;
      }
    }

    return {
      title: `"${wx.getStorageSync('mallName')}" ${wx.getStorageSync('share_profile')}`,
      query: params,
    };
  },

  // onShareAppMessage: function () {
  //   return {
  //     title: `"${wx.getStorageSync('mallName')}" ${wx.getStorageSync('share_profile')}`,
  //   };
  // },

  // onShareTimeline() {
  //   return {
  //     title: `"${wx.getStorageSync('mallName')}" ${wx.getStorageSync('share_profile')}`,
  //   };
  // },

  // 下拉刷新
  onPullDownRefresh() {
    this.resetArticleList();
    this.loadArticles().then(() => {
      wx.stopPullDownRefresh();
    });
  }
})